from django.db import models
from django.utils import timezone

class YzhResourceCategory(models.Model):
    """资源分类模型"""
    name = models.CharField(max_length=50, verbose_name='分类名称')
    description = models.CharField(max_length=255, null=True, blank=True, verbose_name='分类描述')
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'yzh_resource_category'
        verbose_name = '资源分类'
        verbose_name_plural = '资源分类'

    def __str__(self):
        return self.name


class YzhResource(models.Model):
    """资源模型"""
    STATUS_CHOICES = (
        (0, '待审核'),
        (1, '已发布'),
        (2, '已驳回'),
        (3, '已下架'),
    )
    
    TYPE_CHOICES = (
        ('document', '文档'),
        ('ppt', 'PPT课件'),
        ('pdf', 'PDF'),
        ('video', '视频'),
        ('audio', '音频'),
        ('image', '图片'),
        ('code', '代码'),
        ('other', '其他'),
    )
    
    name = models.CharField(max_length=255, verbose_name='资源名称')
    category = models.ForeignKey(YzhResourceCategory, on_delete=models.CASCADE, related_name='resources', verbose_name='分类')
    category_name = models.CharField(max_length=50, null=True, blank=True, verbose_name='分类名称')
    type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='document', verbose_name='资源类型')
    path = models.CharField(max_length=500, verbose_name='资源文件路径')
    size = models.IntegerField(default=0, verbose_name='文件大小(字节)')
    description = models.TextField(null=True, blank=True, verbose_name='资源描述')
    status = models.SmallIntegerField(choices=STATUS_CHOICES, default=0, verbose_name='状态')
    audit_opinion = models.CharField(max_length=500, null=True, blank=True, verbose_name='审核意见')
    download_count = models.IntegerField(default=0, verbose_name='下载次数')
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    creator_id = models.IntegerField(default=0, verbose_name='创建者ID')

    class Meta:
        db_table = 'yzh_resource'
        verbose_name = '教学资源'
        verbose_name_plural = '教学资源'
        ordering = ['-create_time']

    def __str__(self):
        return self.name
        
    def save(self, *args, **kwargs):
        # 自动设置分类名称
        if self.category and not self.category_name:
            self.category_name = self.category.name
        super().save(*args, **kwargs)
